package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author 梁科
 * @Version 1.0
 * @ Date 2025/10/28 16:04
 */
@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Resource
    private AddressBookMapper addressBookMapper;

    /**
     * 增加地址簿
     *
     * @param addressBook
     */
    @Override
    public void addAddressBook(AddressBook addressBook) {
        // 从ThreadLocal中拿到userId
        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        // 增加地址簿时，默认不是默认地址
        addressBook.setIsDefault(0);
        addressBookMapper.insert(addressBook);
    }

    /**
     * 查询当前用户的所有地址簿
     *
     * @param userId
     * @return
     */
    @Override
    public List<AddressBook> getAllAddressBookByUserId(Long userId) {
        List<AddressBook> list = addressBookMapper.getAllByUserId(userId);
        return list;
    }

    /**
     * 根据id查询地址簿
     * @param id
     * @return
     */
    @Override
    public AddressBook getById(Long id) {
        AddressBook addressBook = addressBookMapper.getById(id);
        return addressBook;
    }

    /**
     * 修改地址簿
     * @param addressBook
     */
    @Override
    public void updateAddressBook(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }

    /**
     * 设置默认地址
     * @param id
     */
    @Override
    public void setDefaultAddressById(Long id) {
        Long userId = BaseContext.getCurrentId();
        // 1. 查询该用户的当前默认地址
        AddressBook addressBook1 = AddressBook.builder()
                .isDefault(1)
                .userId(userId)
                .build();
        AddressBook defaultAddress = addressBookMapper.getDefaultAddress(addressBook1);
        if(defaultAddress != null){
            // 2. 将当前默认地址设为非默认地址
            addressBook1.setIsDefault(0);
            addressBook1.setId(defaultAddress.getId());
            addressBookMapper.update(addressBook1);
        }
        // 3. 设置新的默认地址
        AddressBook addressBook = AddressBook.builder()
                .userId(userId)
                .id(id)
                .isDefault(1).build();
        addressBookMapper.update(addressBook);
    }

    /**
     * 查询某个用户的默认地址
     * @param addressBook1
     * @return
     */
    @Override
    public AddressBook getDefaultAddress(AddressBook addressBook1) {
        AddressBook addressBook = addressBookMapper.getDefaultAddress(addressBook1);
        return addressBook;
    }

    /**
     * 根据id删除地址
     * @param id
     */
    @Override
    public void deleteAddress(Long id) {
        addressBookMapper.deleteById(id);
    }
}
